package net.xdclass.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.xdclass.controller.request.ShortLinkAddRequest;
import net.xdclass.controller.request.ShortLinkDelRequest;
import net.xdclass.controller.request.ShortLinkPageRequest;
import net.xdclass.controller.request.ShortLinkUpdateRequest;
import net.xdclass.service.ShortLinkService;
import net.xdclass.util.JsonData;
import net.xdclass.vo.ShortLinkVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 王展
 * @since 2024-07-21
 */
@RestController
@RequestMapping("/api/link/v1")
public class ShortLinkController {
    @Autowired
    private ShortLinkService shortLinkService;
    @Value("${rpc.token}")
    private String rpcToken;

    /**
     * rpc调⽤获取短链信息
     *
     * @return
     */
    @GetMapping("check")
    public JsonData simpleDetail(@RequestParam("shortLinkCode") String shortLinkCode, HttpServletRequest request) {
        String requestToken = request.getHeader("rpc-token");
        if (rpcToken.equalsIgnoreCase(requestToken)){
            ShortLinkVO shortLinkVO = shortLinkService.parseShortLinkCode(shortLinkCode);
            return shortLinkVO == null ?
                    JsonData.buildError("不存在") :
                    JsonData.buildSuccess();
        } else {
            return JsonData.buildError("⾮法访问");
        }
    }
    @PostMapping("add")
    public JsonData createShortLink(@RequestBody ShortLinkAddRequest request){

        JsonData jsonData = shortLinkService.createShortLink(request);

        return jsonData;
    }

    @PostMapping("page")
    public JsonData pageByGroupId(@RequestBody ShortLinkPageRequest request){

        Map page = shortLinkService.pageByGroupId(request);

        return JsonData.buildSuccess(page);
    }

    @DeleteMapping ("del")
    public JsonData DelShortLink(@RequestBody ShortLinkDelRequest request){

        JsonData jsonData = shortLinkService.del(request);

        return jsonData;
    }

    @PutMapping ("update")
    public JsonData DelShortLink(@RequestBody ShortLinkUpdateRequest request){

        JsonData jsonData = shortLinkService.update(request);

        return jsonData;
    }


}

